package com.manman.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.manman.oss.service.OssService;
import com.manman.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    // 上传头像到 oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // 地域节点
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {
            // 创建 OSSClient 实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 获取上传文件流
            InputStream inputStream = file.getInputStream();
            // 获取文件名称
            String fileName = file.getOriginalFilename();
            // 1. 在文件名称里面添加随机唯一值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            String datePath = new DateTime().toString("yyyy/MM");
            fileName = datePath + "/" + fileName;
            // 调用 OSS 方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭 OSSClient
            inputStream.close();
            ossClient.shutdown();

            // 需要把上传到阿里云 oss 路径手动拼接出来
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            System.out.println(url);
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
